import Vue from 'vue'
import axios from 'axios'
import { Loading, Message } from 'element-ui'

Vue.prototype.$globalMsg = {
  success (msg) {
    Message.success({
      message: msg,
      duration:1000
    })
  },
  error (msg) {
    Message.error({
      message: msg,
      duration:1000
    })
  }
}

// 超时时间
axios.defaults.timeout = 10000;
// http请求拦截器
// var loadinginstace;
axios.interceptors.request.use(config => {
   let token = sessionStorage.getItem("Token");
   if (token) {
       config.headers.common['Authorization'] = 'Bearer ' + token
   }
  // config.headers = {
  //   'Content-Type': 'application/json;charset=UTF-8',
  //   'Access-Control-Allow-Origin':'*',
  //   'Accept':'application/json, text/plain, */*'

  // }
  // element ui Loading方法
  // loadinginstace = Loading.service({ fullscreen: true });
  return config;
}, error => {
  // loadinginstace.close();
  // Message.error({
  //   message: '加载超时',
  //   duration:1000
  // })
  window.location.reload();
  return Promise.reject(error);
})

// http响应拦截器
let onetouch=1;
axios.interceptors.response.use((res) => { 
  if (res.data.code == 200) { // 请求成功
    //loadinginstace.close();
    onetouch=1;
    if(res.data.data.token){    
      sessionStorage.setItem('Token', res.data.data.token.accessToken);
      sessionStorage.setItem('refreshToken', res.data.data.token.refreshToken);
    }
    return res.data
  }else if (res.data.code == 401 && onetouch==1) {
    onetouch=0;
    return axios.post('/boss/admin/token/refresh',{'param':sessionStorage.refreshToken})
  }else if (res.data.code == -105) {
    // loadinginstace.close();
    Message.error({
      message: res.data.message,
      duration: 1000
    })
    sessionStorage.clear();
    window.location.reload();
  } else {
    // loadinginstace.close();
    return (res.data);
  }
}, (error) => {
  // loadinginstace.close();
  return Promise.reject(error);
})

Vue.prototype.$axios = axios;

 axios.defaults.baseURL = global.config.requestUrl;
